import random
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        self.ALIBABA_CLOUD_ACCESS_KEY_ID = 'LTAIQRuAM3DlIAa0'
        self.ALIBABA_CLOUD_ACCESS_KEY_SECRET = 'QhcUVAoMQWTd9ptLD2PqtjLImTvmT1'

    def create_client(self) -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id=self.ALIBABA_CLOUD_ACCESS_KEY_ID,
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret=self.ALIBABA_CLOUD_ACCESS_KEY_SECRET
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    def main(self, phone, code):
        client = self.create_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            phone_numbers=phone,
            sign_name='立恒',
            template_code='SMS_166775231',
            template_param=f"{{\"code\":\"{code}\"}}"
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            resp = client.send_sms_with_options(send_sms_request, runtime)
            print("resp>>>", resp.body.code)
            print("resp>>>", type(resp.body.code))
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
        return resp


if __name__ == '__main__':
    spam = Sample()
    code = random.randint(1000, 9999)
    spam.main('15361810411', code)
